package fr.mywiki.view.web.struts.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import fr.mywiki.business.login.LoginManager;
import fr.mywiki.business.resources.ResourceManager;
import fr.mywiki.view.web.struts.form.AccountLogForm;

public class AccountLogAction extends DispatchAction {
	/**
	 * Inits and displays the log panel. At the beginning, no user is logged. The formular is
	 * initialized with no member name.
	 */
	public ActionForward display(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) {
		AccountLogForm form = (AccountLogForm) actionForm;
		form.reset();
		return mapping.findForward("display");
	}
	
	/** Logs the member to the application. The session is now nominative. */
	public ActionForward log(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) {
		AccountLogForm form = (AccountLogForm)actionForm;
		String result = LoginManager.login(form.getLogin(), form.getPassword(), request
				.getSession()); 
		/* Was the connection ok ? */
		if(!LoginManager.CONNECTION_OK.equals(result)) {
			form.reset();
			form.setErrorMessage(request,ResourceManager.getError(result,request.getLocale()));
		}
		return mapping.findForward("display");
	}
	
	/** Unlogs current user from the application. The session is now anonymous. */
	public ActionForward unlog(ActionMapping mapping, ActionForm actionForm,
			HttpServletRequest request, HttpServletResponse arg3) {
		LoginManager.logout(request.getSession());
		return mapping.findForward("display");
	}
}
